package com.vhly.ddxdecompiler.dexreader.util;

import com.vhly.ddxdecompiler.dexreader.file.ClassDefsSection;
import com.vhly.ddxdecompiler.dexreader.file.DexFile;
import com.vhly.ddxdecompiler.dexreader.file.mixeditem.ClassDefItem;
import com.vhly.ddxdecompiler.dexreader.file.mixeditem.StringDataItem;
import com.vhly.ddxdecompiler.dexreader.file.mixeditem.StringIdItem;
import com.vhly.ddxdecompiler.dexreader.file.mixeditem.TypeIdItem;

/**
 * Created by IntelliJ IDEA.
 * User: vhly
 * Date: 2010-12-14
 * Time: 18:41:48
 *
 * @author vhly[FR]
 */

/**
 * Find Util for Dex File operations
 */
public final class FindUtil {
    /**
     * Find Class def
     *
     * @param dex      DexFile
     * @param javaName java package name, if you want find String, you may find java.lang.String
     * @return ClassDefItem
     */
    public static ClassDefItem findClassDef(DexFile dex, String javaName) {
        ClassDefItem ret = null;
        if (dex != null && javaName != null) {
            String vmClassName;
            String[] strs = javaName.split("\\.");  // J2SE Regex
            int len = strs.length;
            StringBuffer sb = new StringBuffer("L");
            if (len > 1) {
                int i;
                for (i = 0; i < len; i++) {
                    sb.append(strs[i]);
                    if (i < len - 1) {
                        sb.append('/');
                    }
                }
            }else{
                sb.append(javaName);
            }
            sb.append(';');
            vmClassName = sb.toString();
            ClassDefsSection defs = dex.getClassDefs();
            int num = defs.size();
            ClassDefItem def;
            for (int i = 0; i < num; i++) {
                def = defs.indexOf(i);
                TypeIdItem idItem = def.getThisItem();
                StringIdItem sid = idItem.getItem();
                StringDataItem sdit = sid.getDataItem();
                if (vmClassName.equals(sdit.value)) {
                    ret = def;
                    break;
                }
            }
        }
        return ret;
    }
}
